<template>
  <div class="image-uploader">
    <van-uploader v-model="fileList" @delete="deleteImg" @oversize="oversize" :preview-full-image="false" :after-read="afterRead" max-count="1" max-size="4194304" />
  </div>
</template>

<script>
import {uploadPic} from '@/util/uploadPic'
import axios from 'axios';

export default {
  props: {
    showIcon: {
      type: String,
      default: ''
    }
  },
  data(){
    return{
      fileList: [],
      icon: ''
    }
  },
  watch: {
    showIcon (val) {
      if (val) {
        this.icon = this.showIcon
        this.fileList = [{url: this.showIcon}]
      }
    }
  },
  computed: {
  },
  methods: {
    deleteImg() {
      this.$emit('iconChange', '');
    },
    suofang (base64, bili = 2, callback) {
      //处理缩放，转格式
      const _img = new Image();
      var _this = this
      _img.src = base64;
      _img.onload = function() {
        var _canvas = document.createElement("canvas");
        var w = this.width / bili;
        var h = this.height / bili;
        _canvas.setAttribute("width", w);
        _canvas.setAttribute("height", h);
        _canvas.getContext("2d").drawImage(this, 0, 0, w, h);
        var newBase64 = _canvas.toDataURL("image/jpeg");
        _canvas.toBlob(function(blob) {
          _this.uploadImg(_this.dataURLtoFile(newBase64))
        }, "image/jpeg");
      }
    },
    dataURLtoFile(dataurl, filename = new Date().getTime() + '.jpeg') {//将base64转换为文件
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while(n--){
          u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {type:mime});
    },
    afterRead(e) {
      this.suofang(e.content)
    },
    oversize() {
      this.$toast('请选择小于4M大小的图片')
    },
    uploadImg(file) {
      const load = this.$toast.loading({
        duration: 0,
        mask: true,
        message: '图片上传中...'
      });
        let fd = new FormData();
      fd.append('icon', this.showIcon);
      fd.append('files',file);
      axios.post('https://app.wpengtao.com:8222/file/upload', fd).then(({data}) => {
        this.$toast.clear();
        console.log(data)
        if(data.code == '200'){
          this.$emit('iconChange', data.message);
          sessionStorage.setItem('lastUploadPic', data.message)
        } else {
          this.$emit('iconChange', '');
          this.$toast('上传失败')
        }
      }).catch(err => {
        this.$toast.clear();
        this.$toast('上传失败')
      });
    }
  }
}
</script>

<style>
.image-uploader{
  padding: 20px 0 ;
  text-align: center;
}
</style>
